<script lang="ts" setup>
import {
  getListByCondition,
  getOneByCondition,
  getOneByConditions,
  getReadonly,
  insertOne,
  reSetDialogModel,
  updateOne,
  urls
} from '@/index';

import type { FormInstance, FormRules } from 'element-plus';
import type { DialogModel, ProjectWeldList, UtTechnique } from '@/index.d';
import { useRequest } from 'vue-request';
import ScanPlan from './ScanPlan.vue';
const dialogModel = defineModel<DialogModel<UtTechnique>>('dialogModel', {
  required: true
});

const { updateForbidden } = getReadonly(dialogModel.value);

const formData = reactive<UtTechnique>({
  id: 0
});

const setFormData = async (res: UtTechnique) => {
  formData.id = res.id;
  formData.creator = res.creator;
  formData.createTime = res.createTime;
  formData.updater = res.updater;
  formData.updateTime = res.updateTime;
  formData.projectId = res.projectId;
  formData.projectName = res.projectName;
  formData.fullName = res.fullName;
  formData.extentName = res.extentName;
  formData.ndeCommissionId = res.ndeCommissionId;
  formData.partName = res.partName;
  formData.partReference = res.partReference;
  formData.testStage = res.testStage;
  formData.testNote = res.testNote;
  formData.scanImageUuid = res.scanImageUuid;
  formData.scanImageUrl = res.scanImageUrl;
};

const reSetFormData = () => {
  reSetDialogModel(dialogModel);
  formData.id = 0;
  delete formData.projectId;
  delete formData.projectName;
  delete formData.fullName;
  delete formData.extentName;
  delete formData.ndeCommissionId;
  delete formData.partName;
  delete formData.partReference;
  delete formData.testStage;
  delete formData.testNote;
  delete formData.scanImageUuid;
  delete formData.scanImageUrl;
};

watch(
  () => dialogModel.value.visible,
  value => {
    value && (formData.id = dialogModel.value.id as number);
    !value && reSetFormData();
  },
  {
    immediate: true
  }
);

watch(
  () => formData.id,
  async (value: number | undefined) => {
    if (value) {
      const res = await getOneByCondition<UtTechnique>(urls.techniqueUtTechnique, 'id', value);
      res && setFormData(res);
    }
  },
  {
    immediate: true
  }
);

const formDataRef = useTemplateRef<FormInstance>('formDataRef');

interface FormDataRules {
  projectId: number;
  fullName: string;
  partReference: string;
  partName?: string;
}

const formDataRules = computed(() => {
  switch (dialogModel.value.type) {
    case 'view':
      return reactive({});

    case 'update':
      return reactive<FormRules<FormDataRules>>({
        projectId: [{ required: true, message: '不能为空', trigger: 'blur' }],
        fullName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        partReference: [{ required: true, message: '不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '不能为空', trigger: 'blur' }]
      });

    case 'insert':
      return reactive<FormRules<FormDataRules>>({
        projectId: [{ required: true, message: '不能为空', trigger: 'blur' }],
        fullName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        partReference: [{ required: true, message: '不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '不能为空', trigger: 'blur' }]
      });
  }
});

const saveFormData = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl
    .validate()
    .then(async valid => {
      if (valid) {
        if (dialogModel.value.id === 0) {
          const res = (await insertOne<UtTechnique>(
            urls.techniqueUtTechnique,
            formData
          )) as UtTechnique;
          if (res) {
            setFormData(res);
            dialogModel.value.id = res.id as number;
            dialogModel.value.type = 'update';
            dialogModel.value.change = true;
          }
        } else {
          const tempFormData: UtTechnique = {
            id: formData.id,
            projectId: formData.projectId,
            fullName: formData.fullName,
            extentName: formData.extentName,
            partReference: formData.partReference,
            partName: formData.partName,
            testStage: formData.testStage,
            testNote: formData.testNote
          };

          const res = (await updateOne<UtTechnique>(
            urls.techniqueUtTechnique,
            tempFormData
          )) as UtTechnique;

          if (res) {
            dialogModel.value.change = true;
            formData.updater = res.updater;
            formData.updateTime = res.updateTime;
          }
        }
      }
    })
    .catch(res => console.log(res));
};

const { data: weldList, run: getWeldList } = useRequest(
  () => getListByCondition<ProjectWeldList>(urls.projectWeldList, 'projectId', formData.projectId!),
  { manual: true }
);

watch(
  () => formData.projectId,
  _value => getWeldList()
);

watch(
  () => formData.partName,
  async (value: string | undefined) => {
    const weldInfo = (await getOneByConditions<ProjectWeldList>(urls.projectWeldList, {
      projectId: formData.projectId,
      partName: value
    })) as ProjectWeldList;
    formData.partReference = weldInfo.partReference;
  }
);

watch(
  () => formData.partReference,
  async (value: string | undefined) => {
    const weldInfo = (await getOneByConditions<ProjectWeldList>(urls.projectWeldList, {
      projectId: formData.projectId,
      partReference: value
    })) as ProjectWeldList;
    formData.partName = weldInfo.partName;
  }
);

watch(
  () => [formData.partName, formData.testStage, formData.extentName],

  ([partName, testStage, extentName]) => {
    formData.fullName =
      partName +
      (testStage === undefined || testStage === '' || testStage === null ? '' : '-' + testStage) +
      (extentName === undefined || extentName === '' || extentName === null
        ? ''
        : '-' + extentName);
  }
);
</script>
<template>
  <HqDialogDetail
    :dialog-model="dialogModel"
    @submit="saveFormData(formDataRef as FormInstance)"
    operate-record
    :operation="formData"
  >
    <template #default>
      <el-card shadow="hover">
        <template #header>基本信息</template>
        <template #default>
          <hq-form :model="formData" ref="formDataRef" :rules="formDataRules">
            <el-row :gutter="5">
              <hq-col v-show="false">
                <el-form-item label="id" prop="id">
                  <el-input v-model="formData.id" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="索引全名称" prop="fullName">
                  <el-input v-model="formData.fullName" readonly />
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="项目名称" prop="projectId">
                  <el-select v-model="formData.projectId" :disabled="updateForbidden">
                    <HqProjectNameOptions />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件名称" prop="partName">
                  <el-select v-model="formData.partName" clearable :disabled="updateForbidden">
                    <el-option
                      v-for="weld in weldList"
                      :key="weld.id"
                      :value="weld.partName!"
                      :label="weld.partName!"
                    />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="工件编号" prop="partReference">
                  <el-select v-model="formData.partReference" clearable :disabled="updateForbidden">
                    <el-option
                      v-for="weld in weldList"
                      :key="weld.id"
                      :value="weld.partReference!"
                      :label="weld.partReference!"
                    />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="检测时机" prop="testStage">
                  <el-select
                    v-model="formData.testStage"
                    clearable
                    :disabled="updateForbidden"
                    placeholder="清选择，如不同检测时机的检测工艺相同，则不选择"
                  >
                    <el-option value="焊后" label="焊后" />
                    <el-option value="热后" label="热后" />
                  </el-select>
                </el-form-item>
              </hq-col>
              <hq-col>
                <el-form-item label="扩展名称" prop="extentName">
                  <el-input v-model="formData.extentName" :readonly="updateForbidden" />
                </el-form-item>
              </hq-col>
            </el-row>
          </hq-form>
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.scanImageUuid">
        <template #header>检测示意图</template>
        <template #default>
          <HqUploadOneImage :key-word="formData.scanImageUuid" :editable="!updateForbidden" />
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.id">
        <template #header>扫查计划</template>
        <template #default>
          <ScanPlan :techniqueId="formData.id" :upddatable="!updateForbidden" />
        </template>
      </el-card>
      <el-card shadow="hover" v-if="formData.id !== 0">
        <template #header>其它信息</template>
        <template #default>
          <hq-form :model="formData" :rules="formDataRules">
            <el-row>
              <el-form-item label="检测备注" prop="scope" style="width: 100%">
                <el-input
                  v-model="formData.testNote"
                  type="textarea"
                  :autosize="{ minRows: 5 }"
                  :readonly="updateForbidden"
                />
              </el-form-item>
            </el-row>
          </hq-form>
        </template>
      </el-card>
    </template>
  </HqDialogDetail>
</template>
<style lang="scss" scoped></style>
